var accessTokenDao = require('../app/components/backend/db').accesstoken,
    vpnserver = require('../app/components/backend/util').vpnserver,
    Promise  = require('bluebird'),
    vpnDao = require('../app/components/backend/db').vpn;
function mockUrl(host, path, option, result) {
  return new Promise(function(resole, reject) {
    resole(nock(host).get(path).query(option).reply(200, result));
  });
}

function makeTokenNeverOutofDate() {
  var testData = {
    access_token: 'BYEsg8wnKAM0d_7uxOjq7E7LgTeCPBw-FQa_-NVUviAMjMSKFD-85Z7rfrJa9vLX4-g3IpDJeKh6EpAp231gofjGokYc23nC9oQ4FX_k2Cs'
  }
  testData.create_time = Date.now();
  return accessTokenDao.upsert({}, testData);
}

function getValueOfXmlNode (nodeName, xmlStr) {
  var re = new RegExp("<" + nodeName + ">(.*?)<\/" + nodeName + ">");
  var value = xmlStr.match(re);
  if (value && value instanceof Array && value.length > 1) {
    value = value[1].replace('<![CDATA[', '').replace(']]>', '');
  } else {
    value = '';
  }
  return value;
}

function prepareVpnData () {
  return Promise.resolve(vpnDao.findOneAndUpdate({host: '192.168.12.55'}, {host: '192.168.12.55', pwd: '111111'}))
    .then(vpnDao.findOneAndUpdate.bind(vpnDao, {host: '192.168.12.100'}, {host: '192.168.12.100', pwd: '222222'}))
    .then(vpnDao.findOneAndUpdate.bind(vpnDao, {host: '192.168.12.212'}, {host: '192.168.12.212', pwd: '333333'}))
    .delay(100).then(vpnserver.init)
    .then(function () {
      vpnserver.setVpnAllocation('192.168.12.55', '000');
      vpnserver.setVpnAllocation('192.168.12.100', '001');
      vpnserver.setVpnAllocation('192.168.12.212', '002');
      vpnserver.setVpnAllocation('192.168.12.55', '003');
      vpnserver.setVpnAllocation('192.168.12.212', '004');
    });
}

function clearVpnData () {
  return  vpnModel.remove({}, function (err) {
    if (err) throw new Error(err);
    return Promise.resolve();
  });
}

function initVpn() {
  return vpnserver.init();
}

function isBluebirdPromise (promise) {
  return (promise &&
  promise.constructor == require('bluebird') &&
  typeof(promise.then) == 'function' &&
  typeof(promise.catch) == 'function' &&
  typeof(promise.delay) == 'function');
}

module.exports = {
  makeTokenNeverOutofDate: makeTokenNeverOutofDate,
  getValueOfXmlNode: getValueOfXmlNode,
  prepareVpnData: prepareVpnData,
  clearVpnData: clearVpnData,
  initVpn: initVpn,
  isBluebirdPromise: isBluebirdPromise
};